<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, { SERVER_BASE_URL } from "@/utils/request.js"

// 路由实例
const router = useRouter()

// 收藏列表数据
const favorites = ref([])
// 加载状态
const loading = ref(false)
// 用户ID
const userId = ref(null)
// 选中的收藏项
const selectedFavorites = ref([])
// 是否显示批量操作按钮
const showBatchActions = ref(false)

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 获取收藏列表
const getFavoritesList = async () => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    const res = await request.get('/favorites/list', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      favorites.value = res.data
    } else {
      ElMessage.error(res.message || '获取收藏夹失败')
    }
  } catch (error) {
    console.error('获取收藏夹失败:', error)
    ElMessage.error('获取收藏夹失败')
  } finally {
    loading.value = false
  }
}

// 取消收藏
const removeFavorite = async (userId, commodityId) => {
  try {
    const res = await request.delete('/favorites/remove', {
      params: { userId, commodityId }
    })
    if (res.code === 200) {
      ElMessage.success('取消收藏成功')
      // 更新本地数据
      favorites.value = favorites.value.filter(item => !(item.userId === userId && item.commodityId === commodityId))
    } else {
      ElMessage.error(res.message || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 清空收藏夹
const clearFavorites = async () => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确定要清空收藏夹吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete('/favorites/clear', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      favorites.value = []
      ElMessage.success('清空成功')
    } else {
      ElMessage.error(res.message || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedFavorites.value = selection
  showBatchActions.value = selection.length > 0
}

// 批量取消收藏
const batchRemoveFavorites = async () => {
  if (selectedFavorites.value.length === 0) {
    ElMessage.warning('请选择要取消收藏的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要取消收藏选中的 ${selectedFavorites.value.length} 个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const promises = selectedFavorites.value.map(item => 
      removeFavorite(item.userId, item.commodityId)
    )
    
    await Promise.all(promises)
    
    // 刷新列表
    getFavoritesList()
    // 清空选择
    selectedFavorites.value = []
    showBatchActions.value = false
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消收藏失败:', error)
      ElMessage.error('批量取消收藏失败')
    }
  }
}

// 跳转到商品详情页
const goToDetail = (id) => {
  router.push(`/commodity/${id}`)
}

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return ''

  // 确保有服务器地址前缀
  let fullUrl = url
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url
  }

  return fullUrl
}

// 页面加载时获取收藏夹数据
onMounted(() => {
  getFavoritesList()
})
</script>

<template>
  <div class="favorites-container">
    <el-card class="favorites-card">

    <div class="favorites-header">
      <h2>我的收藏夹</h2>
      <div class="header-actions">
        <el-button 
          v-if="showBatchActions" 
          type="danger" 
          @click="batchRemoveFavorites"
          :disabled="selectedFavorites.length === 0"
        >
          取消收藏
        </el-button>
        <el-button 
          type="danger" 
          @click="clearFavorites" 
          :disabled="favorites.length === 0"
        >
          清空收藏夹
        </el-button>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="favorites.length === 0" class="empty-container">
      <el-empty description="收藏夹是空的，快去收藏喜欢的商品吧！" />
    </div>

    <el-table
      v-else
      ref="favoriteTable"
      :data="favorites"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <div class="commodity-image">
            <el-image 
              v-if="scope.row.commodity && scope.row.commodity.image && scope.row.commodity.image.length > 0" 
              :src="getImgUrl(scope.row.commodity.image[0])" 
              fit="cover"
              @click="goToDetail(scope.row.commodity.id)"
            >
              <template #error>
                <div class="image-error">暂无图片</div>
              </template>
            </el-image>
            <div v-else class="image-error">暂无图片</div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column show-overflow-tooltip prop="commodity.name" label="商品名称" min-width="150">
        <template #default="scope">
          <div 
            class="commodity-name"
            @click="goToDetail(scope.row.commodity.id)"
          >
            {{ scope.row.commodity.name }}
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="commodity.price" label="价格" width="120">
        <template #default="scope">
          <div class="commodity-price">
            ¥{{ scope.row.commodity.price }}
          </div>
        </template>
      </el-table-column>
      
      <el-table-column show-overflow-tooltip prop="commodity.categoryTag" label="分类" min-width="150">
        <template #default="scope">
          <div class="tag-container">
            <el-tag
              v-for="tag in scope.row.commodity.categoryTag"
              :key="tag"
              size="small"
              type="info"
              effect="plain"
              class="commodity-tag"
            >
              {{ tag }}
            </el-tag>
            <span v-if="!scope.row.commodity.categoryTag || scope.row.commodity.categoryTag.length === 0">
              无分类
            </span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="commodity.status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.commodity.status === 'ON_SALE' ? 'success' : 'info'">
            {{ scope.row.commodity.status === 'ON_SALE' ? '在售' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="收藏时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button 
              type="primary" 
              size="small"
              @click="goToDetail(scope.row.commodity.id)"
            >
              查看详情
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="removeFavorite(scope.row.userId, scope.row.commodityId)"
            >
              取消收藏
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    </el-card>
  </div>
</template>

<style scoped>
.favorites-container {
  padding: 20px;
  max-width: 100%;
  overflow: auto;
}

.favorites-card {
  border-radius: 12px;
  min-height: 80vh;
}

.favorites-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}

.favorites-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-actions {

}

.header-actions .el-button {

}

.commodity-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.commodity-image:hover {
  transform: scale(1.05);
}

.el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
}

.commodity-name {
  font-weight: 500;
  color: #303133;
  cursor: pointer;
  transition: color 0.3s;
}

.commodity-name:hover {
  color: #409EFF;
  text-decoration: underline;
}

.commodity-price {
  font-weight: bold;
  color: #ff6700;
}

.commodity-sales {
  color: #909399;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.commodity-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.loading-container,
.empty-container {
  margin-top: 50px;
  text-align: center;
}

/* 表格操作按钮间距 */
.operation-buttons .el-button + .el-button {
  margin-top: 5px;
}

/* 表格操作按钮居中 */
.operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.operation-buttons .el-button {
  margin-left: 0 !important;
  width: 100px;
}

/* 自定义勾选框样式 */
:deep(.el-table__header .el-checkbox__inner),
:deep(.el-table__body .el-checkbox__inner) {
  width: 20px;
  height: 20px;
}

:deep(.el-checkbox__inner::after) {
  width: 6px;
  height: 10px;
  left: 6px;
  top: 2px;
}
</style>